package com.sanyue.codingsettlement.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.sanyue.codingsettlement.common.ErrorCode;
import com.sanyue.codingsettlement.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author: Guan
 **/
@Slf4j
public class ExcelUtils {

    public static String excelToCsv(MultipartFile multipartFile){
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("表格处理错误", e);
        }
        if (CollUtil.isEmpty(list)) {
            return "";
        }
        StringBuilder str = new StringBuilder();
        for(int i = 0; i < list.size() ; i++ ){
            Map<Integer, String> integerStringMap = list.get(i);
            for (Map.Entry<Integer, String> entry : integerStringMap.entrySet()) {
                if(!StringUtils.isBlank(entry.getValue())){
                    str.append(entry.getValue()).append(",");
                }
            }
            if(str.length() > 0){
                str.deleteCharAt(str.length() - 1);
            }
            if(i != list.size() - 1){
                str.append("\n");
            }
        }

        return str.toString();
    }

    public static void main(String[] args) {
        String data = excelToCsv(null);
        System.out.println(data);
    }
}
